package services;

import objetos.ClienteObj;
import objetos.ItemVendaObj;
import objetos.VendaObj;

import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;

import classes.CarrinhoCompraImpl;
import classes.ClienteImpl;
import classes.VendaImpl;

import java.lang.Float;
import java.util.Iterator;
import java.util.LinkedList;

public class VendaService {

	public OMElement efetuarVenda(OMElement element) {
		
		VendaImpl vi =  new VendaImpl();
		
		// Cria elemento de retorno
		OMFactory factory = OMAbstractFactory.getOMFactory();
		OMNamespace ns_return = factory.createOMNamespace("return", "ret");
		OMElement return_element = factory.createOMElement("return", ns_return);
		
		Iterator<OMElement> it = element.getChildElements();
		
		VendaObj venda = new VendaObj();
		venda.loadOMElement(it.next());
		
		Iterator<OMElement> it_itens = it.next().getChildElements();
		
		LinkedList<ItemVendaObj> itens = new LinkedList<ItemVendaObj>();
		while (it_itens.hasNext()) {
			ItemVendaObj item = new ItemVendaObj();
			item.loadOMElement(it_itens.next());
			itens.add(item);
		}
		
		Boolean retorno = vi.efetuarVenda(venda, itens);
		
		// Preenche retorno
		return_element.setText(retorno.toString());
		
		return return_element;
	}
	
	public OMElement historicoVendasCliente(OMElement element) {
		
		OMFactory fac = OMAbstractFactory.getOMFactory();
		OMNamespace ns_ret = fac.createOMNamespace("return", "ret");
		OMElement return_element = fac.createOMElement("lista", ns_ret);
		
		VendaImpl vi = new VendaImpl();
		
		LinkedList<VendaObj> list = vi.historicoVendasCliente(Integer.parseInt(element.getText()));
		Iterator<VendaObj> it = list.iterator();
		
		while(it.hasNext())
			return_element.addChild(it.next().toOMElement());

		return return_element;
	}
	
	public OMElement calcularFrete(OMElement element) {
		
		VendaImpl vi = new VendaImpl();
		
		Float frete = vi.calcularFrete(element.getText());
		
		element.setText(frete.toString());
		
		return element;
	}
	
	public OMElement cancelarVenda(OMElement element) {
		
		VendaImpl vi = new VendaImpl();
		
		Integer codigoVenda = Integer.parseInt(element.getText());
		
		Boolean retorno = vi.cancelarVenda(codigoVenda);
		
		element.setText(retorno.toString());
		
		return element;
	}
	
	public OMElement definirFormaPagamento(OMElement element) {
	
		VendaImpl vi = new VendaImpl();
		
		Float valorVenda = Float.parseFloat(element.getText());
		
		vi.definirFormaPagamento(valorVenda);
		
		return element;
	}

}
